<?php


namespace App\Services\Wechat;

use App\Models\Period;
use App\Models\Goods;
use DB;

class Qishu
{


    public function __construct
    (
        Period $period,
        Goods $goods
    )
    {
        $this->period = $period;
        $this->goods = $goods;
    }

    public function generateYungouCode($goodsId,$renci)
    {
        $tableName = 'he_code_'.$goodsId;
        $renci = intval($renci);
        $res = DB::select("select count(id) as nums from $tableName");//TODO:优化到 mc 里面去,云购码数量查询 mc,
        if (!$res || $res[0]->nums < $renci) {
            return false;
        }
        DB::beginTransaction();
        try {
            $res = DB::select("select id from $tableName ORDER BY rand() LIMIT $renci");
            $id = '';
            $ids = '';
            foreach($res as $v) {
                $ids .= ','.$v->id;
                $id .= ($v->id+10000000).',';
            }
            $ids = trim($ids, ',');
            DB::delete("delete from $tableName where id in ($ids)");
            DB::commit();
            return $id;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }

}